# @author:Wei Junjie
# @time:2024/5/26 14:18
# @file njav.py
# --*--coding: utf-8 --*--
"""
selenium + request
"""
import time
from pprint import pprint

import requests,re
from PrivateSpider.Log_info import my_log
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

class NjavSpider:
        # self.log = my_log.Mylogger('debug')

    def first_page(self):
        import requests
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        }

        params = {
            'keyword': 'SONE-218',
            'page': '1',
        }
        try:
            response = requests.get('https://njav.tv/en/search', params=params, headers=headers)
            url_list=re.findall('<img.*title="(.*?)"',response.text)
            return url_list
        except Exception as e:
            return


    def second_page(self,designation):
        driver = webdriver.Chrome()
        driver.get('https://njav.tv/en/v/'+designation)
        driver.maximize_window()
        driver.implicitly_wait(10)
        time.sleep(20)
        driver.switch_to.frame(driver.find_element(By.CSS_SELECTOR, '#player>iframe'))
        time.sleep(3)
        driver.switch_to.default_content()
        # 找到iframe的部分地址 https://javplayer.me/v/2LGGLV38
        source_url=re.search('iframe.*?"(.*?)\?',driver.page_source).group(1)
        print(source_url)
        return source_url


    def finally_page(self,from_second_page):
        headers = {

            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
        }
        try:
            response = requests.get(from_second_page,  headers=headers)
            # 通过第二页的地址获取m3u8文件
            res=re.search(r'(https:.*m3u8)', response.text).group(1)
            print(''.join(res.split('\\')))
        except Exception as e:
            return

    def main(self):
        data_list=self.first_page()
        for data in data_list:
            url=self.second_page(data)
            self.finally_page(url)
            time.sleep(5)



if __name__ == '__main__':
    nj=NjavSpider()
    nj.main()


